<template>
	<div>

		<a-card :borderd="false" class="mb-2">
			<a-row :gutter="8">
				<a-col :span="2">
					<a-input v-model:value="config.listQuery.name" placeholder="请输入名称"/>
				</a-col>
				<a-col :span="2">
					<a-input v-model:value="config.listQuery.description" placeholder="请输入描述"/>
				</a-col>
				<a-col :span="2">
					<a-select v-model:value="config.listQuery.defaultPassType" placeholder="请选择默认放行类型"
							  allow-clear
							  style="width:100%">
						<a-select-option v-for="item in config.selectObj.passType" :key="item.value"
										 :value="item.value">{{ item.label }}
						</a-select-option>
					</a-select>
				</a-col>
				<a-col :span="2">
					<a-select v-model:value="config.listQuery.enable" placeholder="请选择启用状态" allow-clear
							  style="width:100%;">
						<a-select-option v-for="item in config.selectObj.statusOptions" :key="item.value"
										 :value="item.value">{{ item.label }}
						</a-select-option>
					</a-select>
				</a-col>
				<a-col :span="12">
					<a-space>
						<a-button @click="tableRef.refresh()">搜索
						</a-button>
						<a-button @click="handleCreate" type="primary">新增
						</a-button>
					</a-space>
				</a-col>
			</a-row>
		</a-card>

		<a-card>
			<h-table :paged="true" ref="tableRef" :data="getList" :columns="columns">
			</h-table>

		</a-card>


		<a-modal v-model:open="config.dialogFormVisible" :destroyOnClose="true" :width="1000" :closable="false"
				 @cancel="config.dialogFormVisible = false" @ok="saveData">
			<a-form :rules="config.rules" ref="dataForm" :model="config.temp"
			>
				<a-form-item label="名称" name="name">
					<a-input placeholder="名称" v-model:value="config.temp.name"></a-input>
				</a-form-item>

				<a-form-item label="描述" name="desc">
					<a-input type="textarea" :autosize="{ minRows: 2, maxRows: 4 }" placeholder="描述"
							 v-model:value="config.temp.description"></a-input>
				</a-form-item>

				<a-form-item label="默认放行类型" name="defaultPassType">
					<a-tooltip content="当IP地址不能匹配任何规则时，默认执行的放行类型"
							   placement="bottom">
						<a-select v-model:value="config.temp.defaultPassType"
								  :disabled="config.dialogStatus === 'update'">
							<a-select-option v-for="item in config.passTypeList" :key="item.key"
											 :value="item.value">
								{{ item.key }}
							</a-select-option>
						</a-select>
					</a-tooltip>
				</a-form-item>

			</a-form>

		</a-modal>

		<a-modal v-model:open="config.dialogPvVisible" :destroyOnClose="true" :width="1000" :closable="false"
				 @cancel="config.dialogPvVisible = false" @ok="config.dialogPvVisible = false">
			<el-table :data="config.pvData" border fit highlight-current-row style="width: 100%">
				<el-table-column prop="key" label="Channel"></el-table-column>
				<el-table-column prop="pv" label="Pv"></el-table-column>
			</el-table>
		</a-modal>

		<a-modal v-model:open="config.dialogBindPortMappingVisible" :destroyOnClose="true" :width="1000"
				 :height="600"
				 :footer="null">
			<h-table :paged="true" ref="portMappingTableRef" :data="getPortMappingList" :columns="portMappingColumns">
			</h-table>
		</a-modal>

	</div>
</template>

<script setup>
import securityGroupApi from '@/api/securityGroup/securityGroupApi.js'
import portMappingApi from '@/api/portMapping/portMappingApi.js'
import {useRouter} from "vue-router";

const tableRef = ref()
const portMappingTableRef = ref()
const dataForm = ref()

const config = ref({
	tableKey: 0,
	list: [],
	total: null,
	listQuery: {
		name: undefined,
		description: undefined,
		defaultPassType: undefined,
		enable: undefined
	},
	listLoading: true,
	temp: {
		id: undefined,
		name: '',
		description: '',
		defaultPassType: undefined
	},
	selectObj: {
		statusOptions: [{label: '启用', value: 1}, {label: '禁用', value: 2}],
		onlineOptions: [{label: '在线', value: 1}, {label: '离线', value: 2}],
		passType: [{label: '允许', value: 1}, {label: '拒绝', value: 0}]

	},
	dialogFormVisible: false,
	dialogStatus: '',
	textMap: {
		update: '编辑',
		create: '新建'
	},
	passTypeList: [{key: '允许', value: 1}, {key: '拒绝', value: 0}],
	dialogPvVisible: false,
	pvData: [],
	rules: {
		name: [{required: true, message: '安全组名称必填', trigger: 'blur'}],
		defaultPassType: [{required: true, message: '默认放行类型必选', trigger: 'blur'}]
	},
	downloadLoading: false,
	checkBoxData: [], //表单勾选的行
	dialogBindPortMappingVisible: false,
	forBindProtMappingSecurityGroup: {},
	portMappingList: [],
	portMappingTotal: null,
	portMappingListLoading: false,
	portMappingListQuery: {
		importance: undefined,
		title: undefined,
		type: undefined,
		userId: undefined,
		license: undefined,
		port: undefined,
		isOnline: undefined,
		enable: undefined,
		description: undefined
	},
})

const columns = ref([
	{
		title: 'id',
		key: 'id',
		dataIndex: 'id',
		ellipsis: true,
	},
	{
		title: '名称',
		key: 'name',
		dataIndex: 'name',
		ellipsis: true,
	},
	{
		title: '描述',
		key: 'description',
		dataIndex: 'description',
		ellipsis: true,
	},
	{
		title: '默认放行类型',
		key: 'defaultPassType',
		dataIndex: 'defaultPassType',
		ellipsis: true,
		mapping: [
			{
				key: '1',
				value: 'success'
			},
			{
				key: '0',
				value: 'danger'
			}
		]
	},
	{
		title: '创建时间',
		key: 'createTime',
		dataIndex: 'createTime',
		ellipsis: true,
	},
	{
		title: '修改时间',
		key: 'updateTime',
		dataIndex: 'updateTime',
		ellipsis: true,
	},
	{
		title: '启停状态',
		key: 'enable',
		dataIndex: 'enable',
		ellipsis: true,
		mapping: [
			{
				key: '1',
				value: '启用'
			},
			{
				key: '2',
				value: '停用'
			}
		]
	},
	{
		title: '操作',
		dataIndex: 'action',
		key: 'action',
		width: 520,
		fixed: 'right',
		buttonList: [
			{
				click: (field, record) => {
					handleGoRulePage(record)
				},
				render: (record) => {
					return "配置规则";
				}
			},
			{
				type: "primary",
				click: (field, record) => {
					handleUpdate(record)
				},
				render: (record) => {
					return "编辑";
				}
			},

			{
				click: (field, record) => {
					handleModifyStatus(record, record.enable == 1 ? 2 : 1);
				},
				render: (record) => {
					return record.enable == 1 ? "停用" : "启用";
				}
			},

			{
				click: (field, record) => {
					handleDelete(record)
				},
				render: (record) => {
					return "删除";
				}
			},
			{
				click: (field, record) => {
					handlePortMapping(record)
				},
				render: (record) => {
					return "端口映射绑定";
				}
			}
		]
	}
])
const portMappingColumns = ref([
	{
		title: 'id',
		key: 'id',
		dataIndex: 'id',
		ellipsis: true,
	},
	{
		title: 'licenseName',
		key: 'licenseName',
		dataIndex: 'licenseName',
		ellipsis: true,
	},
	{
		title: '协议',
		key: 'protocal',
		dataIndex: 'protocal',
		ellipsis: true,
	},
	{
		title: '域名',
		key: 'domain',
		dataIndex: 'domain',
		ellipsis: true,

	},
	{
		title: '服务端口',
		key: 'serverPort',
		dataIndex: 'serverPort',
		ellipsis: true,
	},
	{
		title: '客户端IP',
		key: 'clientIp',
		dataIndex: 'clientIp',
		ellipsis: true,
	},
	{
		title: '客户端端口',
		key: 'clientPort',
		dataIndex: 'clientPort',
		ellipsis: true,
	},
	{
		title: '描述',
		key: 'description',
		dataIndex: 'description',
		ellipsis: true,
	},
	{
		title: '启停状态',
		key: 'enable',
		dataIndex: 'enable',
		ellipsis: true,
		mapping: [
			{
				key: '1',
				value: '启用'
			},
			{
				key: '2',
				value: '停用'
			}
		]
	},
	{
		title: '操作',
		dataIndex: 'action',
		key: 'action',
		width: 260,
		fixed: 'right',
		buttonList: [
			{
				click: (field, record) => {
					handleBind(record)
				},
				render: (record) => {
					return record.securityGroupId ? "绑定" : null;
				}
			},
			{
				click: (field, record) => {
					handleUnbind(record)
				},
				render: (record) => {
					return record.securityGroupId && record.securityGroupId == config.forBindProtMappingSecurityGroup.id ? "解绑" : null;
				}
			},

			{
				click: (field, record) => {
				},
				render: (record) => {
					return record.securityGroupId && record.securityGroupId != config.forBindProtMappingSecurityGroup.id ? "已绑定其他安全组" : null;
				}
			},
		]
	}
])
onMounted(() => {
	getList()
	getPortMappingList()
})

const getList = async () => {
	let response = await securityGroupApi.fetchGroupPage(config.value.listQuery);
	return response;
}


const saveData = async () => {
	let b = await dataForm.value.validate();
	if (!b) {
		return
	}
	if (config.value.dialogStatus == 'create') {
		await createData();
	} else {
		await updateData();
	}

}

const getPortMappingList = async () => {
	let response = await portMappingApi.fetchList(config.value.portMappingListQuery);
	return response;
}
const handleModifyStatus =
	async (row, enable) => {
		await securityGroupApi.updateGroupEnableStatus(row.id, enable);
		tableRef.value.refresh()
	}
const resetTemp =
	() => {
		config.value.temp = {
			id: undefined,
			name: '',
			description: '',
			defaultPassType: undefined
		}
	}
const handleCreate =
	() => {
		resetTemp()
		config.value.dialogStatus = 'create'
		config.value.dialogFormVisible = true
		dataForm.value.clearValidate()
	}
const createData = async () => {
	await securityGroupApi.createGroup(config.value.temp);
	config.value.dialogFormVisible = false
	tableRef.value.refresh()
}
const handleUpdate =
	(row) => {
		config.value.temp = Object.assign({}, row) // copy obj
		config.value.dialogStatus = 'update'
		config.value.dialogFormVisible = true
		dataForm.value.clearValidate()
	}
const updateData =
	async () => {
		const tempData = Object.assign({}, config.value.temp)
		await securityGroupApi.updateGroup(tempData);
		config.value.dialogFormVisible = false
		tableRef.value.refresh()
	}
const handleDelete =
	async (row) => {
		await securityGroupApi.deleteGroup({groupId: row.id});
		tableRef.value.refresh()
	}
const router = useRouter()

const handleGoRulePage = (row) => {
	router.push({path: '/proxy/securityRule/index', query: {groupId: row.id}})
}
const handlePortMapping =
	(row) => {
		config.value.dialogBindPortMappingVisible = true
		config.value.forBindProtMappingSecurityGroup = row
	}

const handleBind = async (portMapping) => {
	await portMappingApi.portMappingBindSecurityGroup(portMapping.id, config.value.forBindProtMappingSecurityGroup.id);
	portMappingTableRef.value.refresh()
}
const handleUnbind = async (portMapping) => {
	await portMappingApi.portMappingUnbindSecurityGroup(portMapping.id);
	portMappingTableRef.value.refresh()
}
</script>
